package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JinGuanJiaUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *  金管家
 */
@Service
public class JinGuanJiaApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        ArrayList<String> strings = new ArrayList<>();
        strings.add(memberSourceInfo.getMobileMd5());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", strings);

        String sign = SecureUtil.md5(JSON.toJSONString(paramMap).concat(pushApiKeyParam.getApiSecret()));
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String queryRequestUrl = queryUrl + "?appid="+pushApiKeyParam.getApiCode()+"&sign="+sign;

        log.info("【金管家】撞库开始【queryUrl】{}【paramMap】{}", queryRequestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryRequestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【金管家】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            JSONArray result1 = data.getJSONArray("result");
            Integer status = result1.getJSONObject(0).getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "0")){
                pushApiResult.setPushSuccess(true);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        JSONObject bizMap = new JSONObject();
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("amount", JinGuanJiaUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("car",BaseTypeInfoEnum.Car.getNameByValue(memberSourceInfo.getCar()));
        bizMap.put("house",BaseTypeInfoEnum.House.getNameByValue(memberSourceInfo.getHouse()));
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("purpose",BaseTypeInfoEnum.Yongtu.getNameByValue(memberSourceInfo.getYongtu()));
        bizMap.put("dead_line",BaseTypeInfoEnum.LoanTime.getNameByValue(memberSourceInfo.getLoanTime()));
        bizMap.put("social",JinGuanJiaUtil.getSheBao(memberSourceInfo.getShebao()));
        bizMap.put("overdue",BaseTypeInfoEnum.Yuqi.getNameByValue(memberSourceInfo.getYuqi()));
        bizMap.put("salary","银行代发");
        bizMap.put("work_year","24个月");
        bizMap.put("car_payment",JinGuanJiaUtil.getCar1(memberSourceInfo.getCar()));
        bizMap.put("car_pledge",JinGuanJiaUtil.getCar2(memberSourceInfo.getCar()));
        bizMap.put("accumulation",JinGuanJiaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("insurance",JinGuanJiaUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("points",JinGuanJiaUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("jd",JinGuanJiaUtil.getJd(memberSourceInfo.getBaitiao()));
        bizMap.put("alipay",JinGuanJiaUtil.getHuaBei(memberSourceInfo.getBaitiao()));
        bizMap.put("source","淘金分期");
        bizMap.put("remark","");
        bizMap.put("sex",memberSourceInfo.getSex() == 1 ? "男" : "女");
        String province = memberSourceInfo.getProvince();
        if (StrUtil.endWith(province, "省")) {
            province = memberSourceInfo.getProvince().substring(0, memberSourceInfo.getProvince().length() - 1);
        }
        bizMap.put("area",province);

        List<JSONObject> strings = new ArrayList<>();
        strings.add(bizMap);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("customers", strings);

        String sign = SecureUtil.md5(JSON.toJSONString(paramMap).concat(pushApiKeyParam.getApiSecret()));
        String queryUrl = pushApiKeyParam.getRegisterUrl();
        String queryRequestUrl = queryUrl + "?appid="+pushApiKeyParam.getApiCode()+"&sign="+sign;

        log.info("【金管家】进件开始【queryUrl】{}【paramMap】{}", queryRequestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryRequestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【金管家】进件结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            Integer status = resultObject.getJSONObject("data").getJSONArray("result").getJSONObject(0).getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "0")){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }



    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
